<template>
  <div>
    <div style="margin-bottom: 20px">
      <!-- 查找 -->
      <el-space wrap>
        <!-- 用户性别选择 -->
        <el-select v-model="status" placeholder="请选择广告状态">
          <el-option
            v-for="item in adStatusMap"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
        <!-- 请输入优惠券标题 -->
        <el-select v-model="type" placeholder="请选择广告类型">
          <el-option
            v-for="item in optionType"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" @click="onSearch">
          <span class="iconfont icon-sousuo"></span>查找
        </el-button>
        <el-button type="primary" @click="addData">
          <span class="iconfont icon-tianjia"></span>添加
        </el-button>
      </el-space>
    </div>
    <!-- 表格 -->
    <el-table ref="tableRef" border row-key="date" :data="tableData" style="width: 100%">
      <el-table-column
        prop="id"
        label="广告ID"
        align="center"
        sortable
        width="180"
        column-key="date"
      />
      <el-table-column prop="title" label="广告标题" align="center" />
      <el-table-column prop="imgUrl" label="广告图片" align="center">
        <template #default="scope">
          <el-popover
            :width="300"
            popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"
          >
            <template #reference>
              <img class="tableImg" :src="scope.row.imgUrl? scope.row.imgUrl:''" />
            </template>
            <template #default>
              <div
                class="demo-rich-conent"
                style="display: flex; gap: 16px; flex-direction: column"
              >
                <img :src="scope.row.imgUrl? scope.row.imgUrl:''" />
              </div>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="广告类型" align="center">
        <template #default="scope">
          <el-tag>
            <!-- //广告类型事件 -->
            {{advertType(scope.row.type)}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="广告状态" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status==1?'success':'info'">{{ scope.row.status==1? '激活':"冻结"}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="unionType" label="关联类型" align="center">
        <template #default="scope">
          <el-tag type="warning">
            <!-- //关联类型事件 -->
            {{associationType(scope.row.unionType)}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="unionValue" label="关联值[ID]" align="center">
        <template #default="scope">{{ scope.row.unionValue? scope.row.unionValue:"无"}}</template>
      </el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间" align="center">
        <template
          #default="scope"
        >{{ scope.row.gmtCreate? new Date().format(scope.row.gmtCreate):"无"}}</template>
      </el-table-column>
      <el-table-column prop label="操作" align="center">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="primary" @click="handleDelete(scope.row,scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 弹框 -->
    <el-dialog v-model="dialogFormVisible" :title="advertFormTitle">
      <el-form
        ref="ruleFormRef"
        :model="formData"
        label-position="left"
        label-width="auto"
        status-icon
        :rules="rules"
      >
        <el-form-item prop="title" label="广告标题">
          <el-input style="width: 180px" v-model="formData.title" />
        </el-form-item>
        <el-form-item label="广告类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择广告类型">
            <el-option
              v-for="item in adTypeMap"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="广告图片:" prop="imgUrl ">
          <el-upload
            class="avatar-uploader"
            action="http://192.168.1.188:8080/upload/admin"
            list-type="picture-card"
            :on-success="handleAvatarSuccess"

            :headers="headers"
          >
              <canvas v-show="false" id="canvas" />
            <template v-if="advertFormTitle=='编辑'" #default>
              <img :src="formData.imgUrl" class="avatar" />
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="广告状态" prop="status ">
          <el-switch
            v-model="formData.status"
            :active-color="formData.status==1? '#13ce66':'#ff4949'"
            :inactive-value="0"
            :active-value="1"
          />
        </el-form-item>
        <el-form-item label="关联类型" prop="unionType">
          <el-select
            v-model="formData.unionType"
            placeholder="请选择关联类型"
            :disabled="formData.type==''"
          >
            <el-option
              v-for="item in adUnionTypeMap"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="formData.unionType==4" label="功能页面" prop="unionType">
          <el-select v-model="formData.unionValue" placeholder="请选择一个功能页面">
            <el-option
              v-for="item in functionPages"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="formData.unionType==3" label="关键字" prop="unionValue">
          <el-input
            style="width: 350px"
            v-model="formData.unionValue"
            placeholder="点击广告后,用户将得到“此关键字”的商品"
          />
        </el-form-item>
        <el-form-item label="类目" prop="unionValue" v-if="formData.unionType==2">
          <el-cascader
            v-model="formData.unionValue"
            placeholder="关联至类目"
            :options="treeOptions"
            :props="props"
            :show-all-levels="false"
            clearable
          />
        </el-form-item>
        <el-form-item label="商品" prop="unionValue" v-if="formData.unionType==1">
          <el-cascader
            v-model="formData.unionValue"
            placeholder="关联至商品"
            :options="productOptions"
            :props="productProps"
            :show-all-levels="false"
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="Cancel">取消</el-button>
          <el-button type="primary" @click="onSubmit('ruleFormRef')">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- //分页 -->
    <daily-demo v-bind="demo" @pages="pages" @limits="limits"></daily-demo>
  </div>
</template>
<script>
import http from "@/util/http";
import DailyDemo from "@/components/DailyOperation/Demo.vue";
import Cookies from "js-cookie";
// 上传图片的相关引用
import { Plus } from "@element-plus/icons-vue";
// import type { UploadProps } from 'element-plus'
export default {
  components: {
    DailyDemo,
  },
  setup() {
    return {
      Plus,
    };
  },
  data() {
    var text1 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入广告标题"));
      }
      callback();
    };
    return {
      // 删除弹框的布尔值
      dialogVisible: false,
      // 弹框的标题
      advertFormTitle: "",
      // 弹框显示隐藏的布尔值
      dialogFormVisible: false,
      //  弹框图片请求头
      headers: { AdminToken: Cookies.get("token") },
      // 弹框的数据
      formData: {
        type: "", //广告类型
        unionType: "", //关联类型
        title: "", //广告标题
        unionValue: "", //关联值
        imgUrl: "", //	广告图片地址
        status: 1, //广告状态
        color: "",
      },
      adId: "", //广告ID
      // 商品获取SPU树配置选项
      productProps: {
        checkStrictly: true,
        label: "label",
        value: "id",
        children: "children",
        emitPath: false,
      },
      // 类目树配置选项
      props: {
        checkStrictly: true,
        label: "title",
        value: "id",
        children: "childrenList",
        emitPath: false,
      },
      // 商品获取SPU树children
      productOptions: [],
      // 类目树
      treeOptions: [],
      // ====渲染数据====
      tableData: [], //广告渲染数据
      // 分页数据
      demo: {
        page: 1,
        limit: 10,
        total: 1, //分页--总条数
      },
      //----------- 查询的信息-------------
      title: "", //查询标题
      type: "", //查询类型
      status: "", //查询状态

      // 规则
      rules: {
        title: [//广告标题不能为空
          {
            validator: text1,
            trigger: "blur",
            required: true,
            message: "广告标题不能为空",
          },
        ],
        type: [//请选择广告类型
          {
            trigger: "blur",
            required: true,
            message: "请选择广告类型",
          },
        ],
        unionType: [//请选择关联类型
          {
            trigger: "change",
            required: true,
            message: "请选择关联类型",
          },
        ],
        status: [//状态
          {
            trigger: "blur",
            required: true,
          },
        ],
        unionValue: [//请关联一个(商品 类目 页面等具体的值)
          {
            trigger: "change",
            required: true,
            message: "请关联一个(商品 类目 页面等具体的值)",
          },
        ],

      },
      adTypeMap: [
        { value: 1, unionTypes: [1, 2, 3, 4], picRequire: true, name: "轮播" },
        { value: 2, unionTypes: [2], picRequire: true, name: "分类精选" },
        { value: 3, unionTypes: [1, 2, 3, 4], picRequire: true, name: "横幅" },
        {
          value: 4,
          unionTypes: [1, 2, 3, 4],
          picRequire: true,
          name: "首页轮播下5按钮",
        },
        { value: 6, unionTypes: [1, 2, 3, 4], picRequire: false, name: "公告" },
        { value: 9, unionTypes: [1], picRequire: false, name: "商品推荐" },
      ],
      //4种广告关联类型
      adUnionTypeMap: [
        { value: 1, name: "商品" },
        { value: 2, name: "类目" },
        { value: 3, name: "关键字" },
        { value: 4, name: "功能页面" },
      ],
      //广告状态
      adStatusMap: [
        { value: 0, name: "冻结" },
        { value: 1, name: "激活" },
      ],
      //功能页面
      functionPages: [
        { value: "/pages/product/groupshop", name: "团购列表" },
        { value: "/pages/coupon/list", name: "优惠券列表" },
      ],
      // 广告类型
      optionType: [
        { name: "轮播", value: 1 },
        { name: "分类精选", value: 2 },
        { name: "横幅", value: 3 },
        { name: "首页轮播下5按钮", value: 4 },
        { name: "公告", value: 6 },
        { name: "商品推荐", value: 9 },
      ],
    };
  },
  watch: {
    formData: {
      deep: true,
      handler(val) {
        let { type } = val;
        if (type == 9) {
          this.adUnionTypeMap = [{ value: 2, name: "商品" }];
          this.formData.unionType = 1;
        } else if (type == 2) {
          this.adUnionTypeMap = [{ value: 2, name: "类目" }];
          this.formData.unionType = 2;
        } else {
          this.adUnionTypeMap = [
            { value: 1, name: "商品" },
            { value: 2, name: "类目" },
            { value: 3, name: "关键字" },
            { value: 4, name: "功能页面" },
          ];
        }
      },
    },
  },
  created() {
    this.advertMan();
      // 类目树与商品树
      this.treeList();

  },
  methods: {
    // 删除
    handleDelete(row) {
      ElMessageBox.confirm("确定要删除此数据吗?", "注意", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let Data = {
            _gp: "admin.advert",
            _mt: "delete",
            type: row.type,
            adId: row.id,
          };
          http.post(Data).then((res) => {
            if (200 == res.data.errno) {
              ElMessage.success("删除成功");
              this.advertMan();
            }
          });
        })
        .catch(() => {
          ElMessage.info("取消删除");
        });
    },
    // 编辑
    handleEdit(row) {
      // 类目树与商品树
        this.treeList();
      Object.assign(this.formData, row); //把当行数据赋值给this.formData---表格数据
      this.advertFormTitle = "编辑";
      this.dialogFormVisible = true;
      this.adId = row.id;

        if (this.tableData.unionType == 2 || this.tableData.unionType == 1) {
        this.tableData.unionValue = parseInt(row.unionValue);
      }
      //  this.CommodityCategories();递归的数据
      console.log(row, this.formData.adId);
    },
    // 取消
    Cancel() {
      if (this.advertFormTitle == "创建") {
        ElMessage.success("取消添加");
      } else {
        ElMessage.success("取消编辑");
      }

      this.dialogFormVisible = false;
      this.advertMan();
    },
    //图片颜色
    getImgColor(img, canvas) {
      console.log(img, canvas, 999);
      canvas.width = img.width;
      canvas.height = img.height;
      let context = canvas.getContext("2d"); //<img> 标签
      context.drawImage(img, 0, 0);
      console.log(img, 99);
      // 获取像素数据
      let data = context.getImageData(0, 0, img.width, img.height).data;
      console.log(context.getImageData(0, 0, img.width, img.height).data);
      let r = 0;
      let g = 0;
      let b = 0;
      // 取所有像素的平均值
      for (var row = 0; row < img.height; row++) {
        for (var col = 0; col < img.width; col++) {
          r += data[(img.width * row + col) * 4];
          g += data[(img.width * row + col) * 4 + 1];
          b += data[(img.width * row + col) * 4 + 2];
        }

      }
      console.log(r,g,b,11111111111111111111111);
      // 求取平均值
      r = r / (img.width * img.height);
      g = g / (img.width * img.height);
      b = b / (img.width * img.height);
      // 将最终的值取整
      r = Math.round(r);
      g = Math.round(g);
      b = Math.round(b);

      return "rgb(" + r + "," + g + "," + b + ")";
    },
    // 点击弹框确定
    onSubmit(ruleFormRef) {
               let img = document.getElementsByClassName(
        "el-upload-list__item-thumbnail"
      )[0];
      let canvas = document.getElementById("canvas");
      this.$refs[ruleFormRef].validate((valid) => {
        if (valid) {
            // 图片颜色
              if (this.formData.imgUrl) {
            this.formData.color = this.getImgColor(img, canvas);
            console.log(this.formData.color);
          }
          if (this.advertFormTitle == "创建") {
            // 添加的弹框---（创建）
            if (this.formData.imgUrl) {
              this.formData.color = "rgb(255,255,255)";
            } else {
              this.formData.color = "rgb(0.5,0.5,0.5)";
              this.formData.imgUrl =
                "http://img.zxwyit.com/admin.shopmall.com/f070c1171e97499a85a1b19956b4911a.png";
            }
            let Data = {
              _gp: "admin.advert",
              _mt: "create",
              ...this.formData,
            };
            http.post(Data).then((res) => {
              console.log(res, "创建成功");
              if (200 == res.data.errno) {
                ElMessage.success("创建成功");
                this.dialogFormVisible = false;
                this.advertMan();
              }
            });
          } else {
            // 编辑的弹框
            let Data = {
              _gp: "admin.advert",
              _mt: "edit",
              ...this.formData,
              adId: this.adId,
            };
            http.post(Data).then((res) => {
              console.log(res, "编辑成功");
              if (200 == res.data.errno) {
                ElMessage.success("编辑成功");
                this.dialogFormVisible = false;
                this.advertMan();
              }
            });
          }
        } else {
          ElMessage.success("表单验证失败");
        }
      });
    },
    // 类目树请求--与--   //商品获取SPU树
    treeList() {
      // 类目树请求
      let treeData = {
        _gp: "admin.category",
        _mt: "categoryTree",
      };
      http.post(treeData).then((res) => {
        this.treeOptions = res.data.data;
        this.advertMan();
      });
      //商品获取SPU树
      let productData = {
        _gp: "admin.product",
        _mt: "getSpuBigTree",
      };
      http.post(productData).then((res) => {
        this.productOptions = res.data.data;

        console.log(res.data.data, "树");

        this.advertMan();
      });
      // let id = this.adId;
      // function recu(tree, parent, id, result) {
      //   for (let i = 0; i < tree.length; i++) {
      //     var item = tree[i];
      //     item.parent = parent;
      //     if (id == item.value) {
      //       Object.assign(result, item);
      //       return;
      //     }
      //     var children = item.children;
      //     if (children) {
      //       recu(tree, parent, id, result);
      //     }
      //   }
      // }
      // let find = {};
      // recu(this.productOptions, null, id, find);
      // var path = [find.value];
      // var item = find.parent;
      // for (; item; ) {
      //   if (item) {
      //     Object.unshift(item.value);
      //   }
      //   item = item.parent;
      // }
      // return path;
    },
    // 成功上传图片---处理化身成功
    handleAvatarSuccess(res, file) {
      let { errno, url } = res;
      if (200 == errno) {
        this.$nextTick(() => {
          this.formData.imgUrl = url;
        });
      } else {
        ElMessage.warning("图片上传失败");
      }
    },

    // 点击添加
    addData() {

      this.formData.title = "";
      this.formData.type = "";
      this.formData.unionType = "";
      this.formData.unionValue = "";
      this.formData.imgUrl = "";
      this.formData.status = 0;
      this.formData.color = "";

      this.dialogFormVisible = true;
      this.advertFormTitle = "创建";
    },
    // 查找
    onSearch() {
      this.advertMan();
    },
    // 广告类型
    advertType(ty) {
      for (const items of this.optionType) {
        //forof循环数组
        if (ty == items.value) {
          //如果广告类型的数值等于value
          return items.name; //就返回与value相对应的label值
        }
      }
    },
    // 关联类型
    associationType(ty) {
      if (ty == 1) {
        return "商品";
      } else if (ty == 2) {
        return "类目";
      } else if (ty == 3) {
        return "关键字";
      } else if (ty == 4) {
        return "功能页面";
      }
    },
    // 广告列表渲染请求
    advertMan() {
      let data = {
        _gp: "admin.advert",
        _mt: "list",
        pageNo: this.demo.page,
        limit: this.demo.limit,
        title: this.title,
        type: this.type,
        status: this.status,
      };
      http.post(data).then((res) => {
        this.tableData = res.data.data.items;
        this.demo.total = res.data.data.total;
      });
    },
    //分页---当前页数
    pages(e) {
      console.log(e, 456);
      this.demo.page = e;
      this.advertMan();
    },
    // 分页---每页显示条目个数
    limits(e) {
      this.demo.limit = e;
      this.advertMan();
    },
  },
};
</script>

<style lang="less" scoped>
//表格广告图片
.tableImg {
  width: 50px;
  height: 35px;
}
.avatar {
  width: 100%;
  height: 100%;
}
</style>
